package com.bit.cfdi.web.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bit.cfdi.web.dao.EmailDAO;
import com.bit.cfdi.web.domain.Contacto;
import com.bit.cfdi.web.domain.Email;

@Repository
public class EmailDAOImpl extends HibernateDaoSupport implements EmailDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory) throws DataAccessException {
		setSessionFactory(sessionFactory);
	}
	
	@Transactional
	@Override
	public void save(final Email email) throws DataAccessException {
		getHibernateTemplate().saveOrUpdate(email);
	}

	@Transactional
	@SuppressWarnings("unchecked")
	@Override
	public Email getById(final Long id) throws DataAccessException {
		List<Email> emails = getHibernateTemplate().find(
				" from Email as e" +
				" where e.idEmail=?", id);
		return emails.size()>0?emails.get(0):null;
	}

	@Transactional
	@SuppressWarnings("unchecked")
	@Override
	public List<Email> getAll() throws DataAccessException {
		List<Email> emails = getHibernateTemplate().find(
				" from Email as e");
		return emails;
	}
	
	@SuppressWarnings("unchecked")
	@Transactional
	@Override
	public List<Email> getFromContacto(final Contacto contacto)
			throws DataAccessException {
		List<Email> emails = getHibernateTemplate().find(
				"FROM Email as e " +
				"WHERE e.contacto = ? ",
				contacto);
		return emails;
	}

	@Transactional
	@Override
	public void deleteFromContacto(final Contacto contacto)
			throws DataAccessException {
		List<Email> toDelete = getFromContacto(contacto);
		getHibernateTemplate().deleteAll(toDelete);
	}

}
